const mysql = require('mysql2')
const crypto = require('crypto')
const database = 'admin'
// 创建数据库连接
const connection = mysql.createConnection({
  host: 'localhost',
  port: '3307',
  user: 'root',
  password: 'root',
  database
})

// 连接到数据库
connection.connect((err) => {
    if (err) {
      console.error('Error connecting to MySQL:', err)
      return
    }
    console.log(`连接到数据库${database}`)

    // 创建用户表的 SQL 语句
    const createUserTableSQL = `
    create table users(
             user_id INTEGER PRIMARY KEY auto_increment,
                    username varchar(255) UNIQUE not null,
                    password text not null,
                    nickname varchar(20) UNIQUE,
                    email varchar(20) UNIQUE not null,
                    salt varchar(200),
                    session_token text,
                    CONSTRAINT email_unique UNIQUE (email),
                    CONSTRAINT username_unique UNIQUE (username),
                    CONSTRAINT nickname_unique UNIQUE (nickname)
    )
  `

    // 执行创建表的 SQL 语句
    connection.query(createUserTableSQL, (error) => {
        if (error) {
          console.log('User table already exists')
          return
        }

        console.log('User table created successfully')
        const ADMIN_PASSWORD = 'admin'

        const getHash = function (password, salt) {
          return crypto.pbkdf2Sync(password, salt, 100000, 256, 'sha256').toString('hex')
        }
        const addUserSQL = 'INSERT INTO users (username, password, nickname, email, salt) VALUES (?,?,?,?,?)'
        const salt = crypto.randomBytes(64)
        const hash = getHash(ADMIN_PASSWORD, salt)

        // 执行添加用户的 SQL 语句
        connection.query(addUserSQL, ['admin', hash, 'admin', 'admin@qq.com', salt.toString('hex')], (error, results, fields) => {
          if (error) {
            console.log('user admin already exists', error)
          }
          console.log('User admin added successfully')

          //用户表创建成功后创建用户详情表
          
        })
      }
    )
  }
)
module.exports = connection
